package com.example.bot.ws;

import com.alibaba.fastjson.JSONObject;
import com.example.bot.entity.Message;
import com.example.bot.entity.Params;
import com.example.bot.entity.Request;
import com.example.bot.event.Subject;
import com.example.bot.thread.ReconnectTask;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.websocket.*;
import java.io.IOException;
import java.net.URI;

@ClientEndpoint
public class Client {

    private Session session;
    private static Client INSTANCE;


    public Client(String url) throws DeploymentException, IOException {
        session =
                ContainerProvider.getWebSocketContainer().connectToServer(this, URI.create(url));
    }

    private volatile static boolean connecting = false;

    public synchronized static boolean connect(String url) {
        try {
            INSTANCE = new Client(url);
            connecting = false;
            return true;
        } catch (DeploymentException | IOException e) {
            System.out.println("连接失败");
            return false;
        }
    }

    public synchronized static void reConnect() {
        if (!connecting) {
            connecting = true;
            if (INSTANCE != null) {
                INSTANCE.session = null;
                INSTANCE = null;
            }

            ReconnectTask.execute();
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        System.out.println("连接成功");
    }

    @OnMessage
    public void onMessage(String json) throws JsonProcessingException {
        Message message = JSONObject.parseObject(json, Message.class);
//        System.out.println(message);
        if ("message".equals(message.getPost_type())) {
//            Request<Params> paramsRequest = new Request<>();
//            paramsRequest.setAction("send_msg");
//            Params params = new Params();
//            params.setUser_id(message.getUser_id());
//            params.setMessage(message.getMessage());
//            params.setMessage_type("private");
//            params.setAuto_escape(true);
//            paramsRequest.setParams(params);
//            sendMessage(JSONObject.toJSONString(paramsRequest));

            Subject.change(message);
        }
    }

    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
        reConnect();
    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("连接异常");
        reConnect();
    }

    public static void sendMessage(String json) {
        Client.INSTANCE.session.getAsyncRemote().sendText(json);
    }

}
